package com.chen.service.impl;

import cn.hutool.json.JSONUtil;
import com.chen.common.constant.MessageConstant;
import com.chen.common.utils.AliOssUtil;
import com.chen.common.utils.CommonMethod;
import com.chen.common.utils.JwtUtil;
import com.chen.common.utils.Md5Util;
import com.chen.judge.codesandbox.model.JudgeResult;
import com.chen.mapper.ProblemMapper;
import com.chen.mapper.ProblemSubmitMapper;
import com.chen.mapper.UserMapper;
import com.chen.popj.dto.UserChangesPassWordDTO;
import com.chen.popj.dto.UserDTO;
import com.chen.popj.entity.Problem;
import com.chen.popj.entity.ProblemSubmit;
import com.chen.popj.entity.User;
import com.chen.popj.vo.ProblemSubmitVO;
import com.chen.popj.vo.UserVO;
import com.chen.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.UUID;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    HttpServletRequest httpServletRequest;

    @Autowired
    ProblemSubmitMapper problemSubmitMapper;

    @Autowired
    ProblemMapper problemMapper;

    /**
     * 根据用户名查找用户
     *
     * @param username
     * @return
     */
    @Override
    public User queryByUsername(String username) {
        return userMapper.queryByUsername(username);
    }

    /**
     * 注册新用户
     *
     * @param user
     */
    @Override
    public void register(User user) {
        // 对明文密码进行加密
        user.setPassword(Md5Util.getMD5String(user.getPassword()));
        userMapper.register(user);
    }

    /**
     * 用户退出登录
     */
    @Override
    public void quit() {
        String token = httpServletRequest.getHeader("Authorization");
        stringRedisTemplate.delete(token);
    }

    /**
     * 根据用户id查询用户信息
     *
     * @return
     */
    @Override
    public UserVO getUserInfo() {
        Integer userId = CommonMethod.getUserId();
//        System.out.println("userId:" + userId);
        return userMapper.getUserInfo(userId);
    }

    /**
     * 根据用户id修改用户基本资料
     *
     * @param userDTO
     */
    @Override
    public void userInfoUpdate(UserDTO userDTO) {
        User user = User.builder()
                .id(CommonMethod.getUserId())
                .username(userDTO.getUsername())
                .email(userDTO.getEmail())
                .build();
        userMapper.Update(user);
    }

    /**
     * 根据用户id修改密码
     *
     * @param userChangesPassWordDTO
     */
    @Override
    public void userPasswordUpdate(UserChangesPassWordDTO userChangesPassWordDTO) {
        Integer userId = CommonMethod.getUserId();
        if (userId == null) {
            throw new RuntimeException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        String sqlPassword = userMapper.queryPasswordById(userId);
        if (sqlPassword == null) {
            throw new RuntimeException(MessageConstant.USER_PASSWORD_NOT_EXIST);
        }

        String oldPassword = userChangesPassWordDTO.getOldPassword();
        String md5OldPassword = Md5Util.getMD5String(oldPassword);
        if (!sqlPassword.equals(md5OldPassword)) {
            throw new RuntimeException(MessageConstant.OLD_PASSWORD_IS_INCORRECT);
        }

        String newPassword = userChangesPassWordDTO.getNewPassword();
        String md5NewPassword = Md5Util.getMD5String(newPassword);
        User user = User.builder()
                .id(userId)
                .password(md5NewPassword)
                .build();
        userMapper.Update(user);
    }

    /**
     * 根据用户id获取用户个人做题记录
     *
     * @return
     */
    @Override
    public ArrayList<ProblemSubmitVO> getSubmitRecord() {
        Integer userId = CommonMethod.getUserId();
        ArrayList<ProblemSubmit> problemSubmit = problemSubmitMapper.querySubmitRecordByUserId(userId);
        ArrayList<ProblemSubmitVO> problemSubmitVOS = new ArrayList<>();
        for (ProblemSubmit submit : problemSubmit) {
            Problem problem = problemMapper.getById(submit.getProblemId());
            String judgeInfo = submit.getJudgeInfo();
            JudgeResult judgeResult = JSONUtil.toBean(judgeInfo, JudgeResult.class);
            ProblemSubmitVO problemSubmitVO = ProblemSubmitVO.builder()
                    .problemId(submit.getProblemId())
                    .problemTitle(problem.getTitle())
                    .language(submit.getLanguage())
                    .result(judgeResult.getMessage())
                    .submitTime(submit.getSubmitTime())
                    .build();
            problemSubmitVOS.add(problemSubmitVO);
        }
        System.out.println(problemSubmitVOS);
        return problemSubmitVOS;
    }

    /**
     * 用户上传头像
     *
     * @param avatarUrl
     */
    @Override
    public void uploadAvatar(String avatarUrl) {
        Integer userId = CommonMethod.getUserId();
        User user = User.builder()
                .id(userId)
                .avatar(avatarUrl).build();
        userMapper.Update(user);
    }

    /**
     * 获取用户名和头像
     *
     * @return
     */
    @Override
    public UserVO getUserNameAndAvatar() {
        String authorization = httpServletRequest.getHeader("Authorization");
        Map<String, Object> parseToken = JwtUtil.parseToken(authorization);
        String username = (String) parseToken.get("username");
        Integer userId = (Integer) parseToken.get("id");
        String avatarURL = userMapper.getUserAvatar(userId);
        return UserVO.builder()
                .username(username)
                .avatar(avatarURL)
                .build();
    }
}
